<?php
/**
 * Created by PhpStorm.
 * User: 38339
 * Date: 2021-05-26
 * Time: 14:41
 */

namespace app\admin\middleware;
use app\common\business\auth\CommonAdmin as serviceModel;
use app\common\model\auth\CommonAdminActionLog;
use think\facade\Log;

class Auth
{
    /*
     * 这里进行权限验证。验证传入的token是否有效，先检查token是否存在，不存在的话 没必要进行token验证，检查完后将用户数据存储在session里面，还有写入操作日志
     */
    public function handle($request,\Closure $next){
        $noAuthArr = ["login/login"];
        $data = $request->post();
        if(isset($data['token']) && !in_array($request->pathinfo(),$noAuthArr)){
            $admin = serviceModel::checkToken($data['token']);
            session('admin_user',$admin);
        }
        //写入操作日志
        $pathinfo = $request->pathinfo();
        if(!empty($pathinfo)){
            $pathinfo_arr = explode('/',$pathinfo);
            //这里定义不写操作日志的方法
            if(!in_array($pathinfo_arr[count($pathinfo_arr)-1],['login','list','load','listAll','test','parentList'])){
                $admin = session('admin_user');
                $admin_name = $admin['username'].'/'.$admin['mobile'];
                $pathinfo = $request->pathinfo();
                CommonAdminActionLog::insertLog($admin_name,$pathinfo,$data);
            }
        }
        //执行方法
        return $next($request);
    }

}